using System;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Level03Manager : MonoBehaviour
{
    [Header("日月中心点引用")] [SerializeField] private Transform _sunCenterPoint;
    [Header("日月材质引用")] [SerializeField] private Material _sunMaterial;
    [Header("黑暗环境图片引用")] [SerializeField] private Image _darknessImage;
    [Header("按钮图片引用")] [SerializeField] private Image _btnImage;
    [Header("按钮文字引用")] [SerializeField] private TMP_Text _btn_text;

    
    private int _initValue = -90;
    private int _rotationZ;
    private int _dayTime = 10;//一天的时间
    private float _timer;
    private float _dayOrNightProcess;

    private int _setOutTimes = 3;
    private void Awake()
    {
        _rotationZ = _initValue;
    }

    private void Start()
    {
        PlayerController.Instance.HidePlayer();
    }

    private void Update()
    {
        if (_timer >= _dayTime) _timer = 0;
        _timer += Time.deltaTime;
        _dayOrNightProcess = _timer / _dayTime;
        _rotationZ = (int)Mathf.Lerp(_initValue, 270f, _dayOrNightProcess);

        float thresHold = (-Mathf.Sin((_dayOrNightProcess) * 2 * Mathf.PI) + 1) * 0.5f;
        
        _sunMaterial.SetFloat("_DayOrNight", thresHold);
        _sunCenterPoint.transform.rotation = Quaternion.Euler(0, 0, _rotationZ);
        
        _darknessImage.color = new Color(0, 0, 0, Mathf.Clamp(thresHold, 0, 0.9f));

        if (InSetOutRange())
        {
            _btnImage.color = Color.green;
        }
        else
        {
            _btnImage.color = Color.white;
        }
    }

    public void TrySetOut()
    {
        if (InSetOutRange())
        {
            Debug.Log("clearance");
            _setOutTimes--;
            if (_setOutTimes == 0)
            {
                _btn_text.text = "出发！\n次数：" + _setOutTimes;
                
                MapManager.Instance.SetLastSceneIndex(3);
                //UIManager.Instance.ShowClearancePanel();
                GameManager.Instance.Clearance(3);
                enabled = false;
            }
        }
        else
        {
            Debug.Log("fail");
            //_setOutTimes++;
        }

        _btn_text.text = "出发！\n次数：" + _setOutTimes;
    }

    private bool InSetOutRange()
    {
        return _dayOrNightProcess >= 0.2f && _dayOrNightProcess <= 0.3f;
    }
}
